<template>
    <div id="operational">
      <!-- <p>立减活动</p>
      <hr>
      <br>
      <div class="el-alert el-alert--info"><i class="el-alert__icon el-icon-information is-big"></i>
        <div class="el-alert__content">
          <p class="el-alert__description">设置立减活动后，关联商品的价格会直接显示立减后的价格，并将常售价划掉，摆放在当前售价旁边。</p>
          </div>
      </div>
      <br> -->
      <p class="mt20">设置基本信息</p>
      <hr>
      <br>
      <div class="mt20">
        <el-row>
          <el-col :span='10'>
            <el-form :model="form" ref="form" :rules="rules" label-width="100px">
              <el-form-item label="活动主题" prop='name'>
                <el-input v-model="form.name"></el-input>
              </el-form-item>
              <el-form-item label="活动标签" prop='tag'>
                <el-input v-model="form.tag" :maxlength='6' placeholder='6个字以内'></el-input>
              </el-form-item>
              <el-form-item label="生效时间" prop='timeList'>
                <time-picker-group
                  :time-list = 'editParamTimeList'
                  @updateTimeGroup = 'updateForm'
                ></time-picker-group>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <br>
      <p class="mt20">设置促销价格</p>
      <hr>
      <br>
      <div>
        <div>
          <el-button type="primary" icon="plus" @click='callPanel'>添加此活动关联的商品</el-button>
          <span>先选型所需关联的商品</span>
          </div>
      </div>
      <!-- 商品选择面板 -->
      <goods-select-panel
        ref='goodsSelectPanel'
        :prop-item = 'productList'
        @updateProduct = 'changeProductList'
      ></goods-select-panel>

      <!-- 设置价格策略面板 -->
      <strategy-price-table
        ref='strategyPriceTable'
        :productList = 'productList'
        :skuList ='skuList'
        :skuTableList = 'editParam.skuPriceList'
      ></strategy-price-table>
      <br>
      <p style="text-indent:400px">
        <el-button type="primary" size="large" @click='submitForm'>提交</el-button>
      </p>
      <activity-conflict-panel
        ref='activityConflictPanel'
      ></activity-conflict-panel>
      <el-dialog
        v-model="dialogFormVisible"
        :show-close='false'
        :close-on-click-modal='false'
        size='tiny'
      >
        <div>
          <p class="title_tip">创建成功!</p>
          <hr>
        </div>
        <div class="btn_group">
          <p><el-button @click="start()" size="large">直接启动</el-button><el-button @click="addActivity" size="large">继续新增</el-button></p>
        </div>
      </el-dialog>
    </div>
</template>
<script>
import goodsSelectPanel from 'components/operational/goodsSelectPanel.vue'
import timePickerGroup from 'components/operational/timePickerGroup.vue'
import strategyPriceTable from 'components/operational/strategyPriceTable.vue'
import activityConflictPanel from 'components/operational/activityConflictPanel.vue'
import {
  savePriceStrateg,
  savePriceStrategyStart
} from 'src/api/index.js'
export default {
  created () {
    this.$route.meta.breadcrumbData = [
      {
        butRule: '/operational',
        name: '营销管理'
      },
      {
        butRule: '/operational/createLJCampaign',
        name: '新增立减活动'
      }
    ]
  },
  data () {
    return {
      dialogFormVisible: false,
      editParam: {},
      editParamTimeList: [],
      showPanel: false,
      timeList: [],
      productList: [],
      skuList: [],
      strategyId: null,
      form: {
        name: '',
        tag: '',
        timeList: []
      },
      rules: {
        name: [
          {required: true, message: '请填写正确活动主题', trigger: 'blur'}
        ],
        tag: [
          {required: true, message: '请填写正确活动标签', trigger: 'blur'}
        ],
        timeList: [
          {
            required: true,
            validator: function (rule, value, callback) {
              if (value.length === 0) {
                callback(new Error('请设置有效生效时间'))
              }
              value.forEach((item) => {
                if (!item['effectBeginTime']) {
                  callback(new Error('请设置有效生效时间'))
                } else if (!item['effectEndTime']) {
                  callback(new Error('请设置有效生效时间'))
                }
              })
              callback()
            }
          }
        ]
      }
    }
  },
  watch: {
    'form.timeList': {
      deep: true,
      handler: function () {
        this.$refs.form.validateField('timeList')
      }
    }
  },
  methods: {
    callPanel () {
      this.$refs.goodsSelectPanel.showPanel()
    },
    changeProductList (productList) {
      this.productList = [...productList]
    },
    updateForm (timeList) {
      this.form.timeList = timeList
    },
    submitForm () {
      this.validate()
        .then((validateResult) => {
          let skuPriceList = []
          this.$refs.strategyPriceTable.tableData.forEach((item) => {
            let arrItem = {...item}
            arrItem['promotionPrice'] = Number(item['promotionPrice']) * 100
            skuPriceList.push(arrItem)
          })
          return savePriceStrateg({
            activityType: 1,
            name: this.form.name,
            tag: this.form.tag,
            timeList: [...this.form.timeList],
            skuPriceList: skuPriceList
          })
        })
        .then((res) => {
          return new Promise((resolve, reject) => {
            let result = res.data
            if (result.code === 100) {
              if (result.data.failProductList && result.data.failProductList.length > 0) {
                // 出现商品冲突的情况
                resolve({
                  failProductList: result.data.failProductList,
                  cacheKey: result.data.cacheKey
                })
              } else {
                this.dialogFormVisible = true
                this.strategyId = result.data.strategyId
              }
            } else {
              this.$alert(result.message)
            }
          })
        })
        .then(this.handleConflict)
        .catch((result) => {
        })
    },
    validate () {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate(function (result) {
          if (result) {
            resolve(result)
          } else {
            reject(result)
          }
        })
      })
    },
    handleConflict ({failProductList, cacheKey}) {
      // 处理冲突的情况
      this.$refs.activityConflictPanel.callPanel(failProductList, cacheKey)
    },
    activityStart () {
      this.$router.push({
        path: '/operational/activitiesList'
      })
    },
    addActivity () {
      this.$router.push({
        path: '/operational/createCampaign'
      })
    },
    start () {
      let that = this
      let id = this.strategyId
      this.$confirm('将启动编号为' + id + '的营销活动', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        savePriceStrategyStart({
          'priceStrategyId': id
        }).then((res) => {
          let result = res.data
          if (result.code === 100) {
            this.$alert('启动成功', {
              callback: function () {
                that.$router.push({
                  path: '/operational/activitiesList'
                })
              }
            })
          } else if (result.code !== 100) {
            this.$alert('启动失败', {
              callback: function () {
                that.$router.push({
                  path: '/operational/activitiesList'
                })
              }
            })
          }
        })
        .catch(() => {
          this.$alert('启动失败', {
            callback: function () {
              that.$router.push({
                path: '/operational/activitiesList'
              })
            }
          })
        })
      })
      .catch(() => {
        this.$alert('取消启动', {
          callback: function () {
            that.$router.push({
              path: '/operational/activitiesList'
            })
          }
        })
      })
    }
  },
  components: {
    goodsSelectPanel,
    timePickerGroup,
    strategyPriceTable,
    activityConflictPanel
  }
}
</script>
<style>
  #operational .el-alert__description {
    font-size:16px;
  }
</style>
